import React, {PureComponent} from 'react';
import {connect} from 'dva';
import moment from 'moment'
import {Button, Card, DatePicker, Cascader, Form, Icon, InputNumber, Input, Modal, Radio, Select, Tooltip, Upload} from 'antd';

import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './style.less';
import UEditor from '../../ueditor/UMEditor';

const FormItem = Form.Item;
const {Option} = Select;
const {RangePicker} = DatePicker

const {TextArea} = Input;

@connect(state => ({
    slider: state.slider,
    advert:state.advert
}))
@Form.create()
export default class AdvertEdit extends PureComponent {
    state = {
        thumbUrl: '',
        previewVisible: false,
        previewImage: '',
        fileList: [],
        showTime:[],
        thumbFile:''
    }

    componentDidMount() {
       this.loadData();
    }

    loadData=()=>{
        const {dispatch,match} = this.props;
        const id = match.params.id;

        dispatch({
            type:"slider/fetchItem",
            payload:{id},
            callback:()=>{
                const {slider:{item}} = this.props;
                const thumb = item.thumb
                this.setState({
                    thumbFile:thumb.replace('https://zzbj.kooki.cn/',''),
                    thumbUrl:item.thumb,
                })
            }
        })
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                const {dispatch,match} = this.props;
                const id = match.params.id;
                values.id = id;
                dispatch({
                    type: 'slider/edit',
                    payload: values,
                    callback: () => {
                        this.loadData();
                    },
                });
            }
        });
    }

    handleCancel = () => this.setState({ previewVisible: false })

    handlePreview = (file) => {
        console.log(file);
        this.setState({
            previewImage: file.response.data.url,
            previewVisible: true,
        });
    }

    thumbUpload = (info) => {
        if (info.file.status === 'done') {
            const thumbUrl = info.file.response.data.url;
            this.setState({
                thumbUrl,
            });
            return info.file.response.data.file;
        }
    }
    photosChange = ({fileList}) => {
        this.setState({ fileList });
        return this.state.fileList;
    }
    beforeUpload = () => {

    }

    render() {
        const {slider: {options, loading,item},advert:{types}} = this.props;
        const {getFieldDecorator} = this.props.form;
        const thumbUrl = this.state.thumbUrl;
        const { previewVisible, previewImage, fileList } = this.state;
        const uploadButton = (
          <div>
            <Icon type="plus" />
            <div className="ant-upload-text">上传图片</div>
          </div>
        );
        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 7},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 17},
                md: {span: 14},
            },
        };
        const submitFormLayout = {
            wrapperCol: {
                xs: {span: 24, offset: 0},
                sm: {span: 10, offset: 7},
            },
        };
        const rangeConfig = {
            rules: [{ type: 'array', required: true, message: '请选择展示时间' }],
        };
        return (
          <PageHeaderLayout title="编辑轮播" content="编辑轮播，下列的所有内容均需填写">
            <Card bordered={false}>
              <Form
                onSubmit={this.handleSubmit}
                hideRequiredMark
                style={{marginTop: 8}}
              >
                  <FormItem
                      {...formItemLayout}
                      label="缩略图"
                  >
                      <div className="dropbox">
                          {getFieldDecorator('thumb', {
                              valuePropName: 'thumb',
                              getValueFromEvent: this.thumbUpload,
                              initialValue: item.thumb,
                              rules: [{
                                  required: true,
                                  message: '请上传缩略图',
                              }],
                          })(
                              <Upload.Dragger showUploadList={false} name="file" action={`/api/upload?token=${sessionStorage.getItem('access_token')}`}>
                                  {thumbUrl ? <img src={thumbUrl} alt="" className={styles.thumb} /> :
                                      <div>
                                          <p className="ant-upload-drag-icon">
                                              <Icon type="inbox" />
                                          </p>
                                          <p className="ant-upload-text">点击或拖拽上传</p>
                                      </div>}
                              </Upload.Dragger>
                          )}
                      </div>
                  </FormItem>
                <FormItem
                  {...formItemLayout}
                  label={
                    <span>
                  类别
                  <em className={styles.optional}>
                      &nbsp;
                    <Tooltip title="选择需要添加到的类别">
                      <Icon type="info-circle-o" style={{marginRight: 4}} />
                    </Tooltip>
                  </em>
                    </span>
                      }
                >
                  {getFieldDecorator('type', {initialValue: item.type})(
                      <Select >
                          {options.map((item)=>(<Option key={item.value}>{item.label}</Option>))}
                      </Select>
                  )}
                </FormItem>
                  <FormItem
                      {...formItemLayout}
                      label={
                          <span>
                  链接类型
                  <em className={styles.optional}>
                      &nbsp;
                      <Tooltip title="链接类型分为带参数和不带参数两种。详情页面都带参数。需要指定具体的id，才能跳转">
                      <Icon type="info-circle-o" style={{marginRight: 4}}/>
                    </Tooltip>
                  </em>
                    </span>
                      }
                  >
                      <Select onChange={(value)=>{
                          console.log(value)
                          this.props.form.setFieldsValue({page:value})
                      }}>
                          {types.map((item) => (<Option key={item.link}>{item.title}</Option>))}
                      </Select>

                  </FormItem>

                  <FormItem
                      {...formItemLayout}
                      label="跳转链接"
                  >
                      {getFieldDecorator('page', {
                          rules: [{
                              required: true, message: '请输入跳转链接',
                          }],
                          initialValue: item.page
                      })(
                          <Input />
                      )}
                  </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="名称"
                >
                  {getFieldDecorator('name', {
                                rules: [{
                                    required: true, message: '请输入名称',
                                }],
                      initialValue: item.name
                            })(
                              <Input  placeholder="请输入名称" />
                            )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="状态"
                >
                  {getFieldDecorator('status', {initialValue: item.status})(
                    <Radio.Group>
                      <Radio value={0}>禁用</Radio>
                      <Radio value={1}>启用</Radio>
                    </Radio.Group>
                            )}
                </FormItem>

                <FormItem {...submitFormLayout} style={{marginTop: 32}}>
                  <Button type="primary" htmlType="submit" loading={loading}>
                                提交
                  </Button>
                  <Button onClick={() => { this.props.form.resetFields(); }} style={{marginLeft: 8}}>重置</Button>
                </FormItem>
              </Form>
            </Card>
            <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
              <img alt="图片预览" style={{ width: '100%' }} src={previewImage} />
            </Modal>
          </PageHeaderLayout>
        );
    }
}
